<?php

class ClassImageController extends GxController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('makePrimaryImage', 'primaryImage', 'dynamicCity', 'SelectedVenue'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('classimages', 'Courseimagestatus', 'deleteCourseImage', 'courseupload', 'createcoursesuccess', 'createclasssuccess', 'coursePrimaryImage', 'courseimage', 'Delete', 'deleteClassImage', 'Upload'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionclassimages() {
        Yii::import("xupload.models.XUploadForm");
        $photos = new XUploadForm;
        $userImages = '';
        $modelClassImage = new ClassImage;
        $userImages = Yii::app()->user->getState('frontImages');
        $authKey = Yii::app()->user->getState('authKey');
        if (!empty($authKey)) {
            $classes = Classes::model()->findByAttributes(array('auth_key' => $authKey));
            $userId = getLoginUserId();
            if (!empty($classes) && ($userId == $classes->users_id)) {
                if (isset($_POST) && !empty($userImages)) {
                    try {
                        $classCourseImage = ClassImage::model()->findByAttributes(array('classes_id' => $classes->id));
                        $save = self::addClassImage($classes->id);
                        Yii::app()->user->setState('frontImages', NULL);
                        if ($save) {
                            if (empty($classCourseImage)) {
                                $mailmodel = EmailTemplate::model()->findByPk(Message::CREATE_CLASS_COURSE_SUBSCRIBE_USER_NOTIFICATION);
                                $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
                                $userNames = Users::getFrontEndUser($classes->users_id);
                                $userName = $userNames->first_name . '  ' . $userNames->last_name;
                                $mailto = EMAIL_TO_ADMIN;
                                $classCourseName = $classes->class_titile;
                                $viewClassLink = '<a href="http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('workshop-' . $classes->id . '/' . $classes->class_seo_title) . '" class="linkclass" target="_blank">View ' . SkillConfig::CLASS_WORK_SHOP . '</a>';
                                $this->sendMailToSubscribeUser($viewClassLink, $classCourseName, $userName);
                                $arrayFind = array('[username]', '[trainer_name]', '[classcoursename]', '[classCourseViewdetailsLink]');
                                $arrayReplace = array($mailto, $userName, $classCourseName, $viewClassLink);

                                $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                                $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                                $subject = $mailmodel->subject . ' ' . $userName;
                                $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                                try {
                                    SkillSendMail::SendMailCreateCLassCourse($mailto, $subject, $body);
                                    $this->redirect(array('classImage/createclasssuccess/' . $classes->id));
                                } catch (Exception $e) {
                                    echo $e;
                                    exit;
                                }
                            }
                            Yii::app()->user->setState('frontImages', null);
                            if (Yii::app()->getRequest()->getIsAjaxRequest())
                                Yii::app()->end();
                        }
                    } catch (Exception $e) {
                        $transaction->rollback();
                        throw $e;
                    }
                }
                $this->render('_classForm', array(
                    'modelClassImage' => $modelClassImage,
                    'photos' => $photos, 'authKey' => $authKey
                ));
            }
        } else {
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
        }
    }

    public function actioncreateclasssuccess($id) {
        $this->render('_classthankyou', array('id' => $id));
    }

    public function actioncreatecoursesuccess($id) {
        $this->render('_coursethankyou', array('id' => $id));
    }

    private function sendMailToSubscribeUser($viewClassLink, $classCourseName, $trainnername) {
        $subscribeUsers = TrainerFollow::model()->findAll('trainer_front_end_user_id=' . getLoginUserId());
        if (!empty($subscribeUsers)) {
            foreach ($subscribeUsers as $subscribeUser) {
                $follwersName = Users::model()->findByPk($subscribeUser->folower_user_id);
                $mailmodel = EmailTemplate::model()->findByPk(Message::CREATE_CLASS_COURSE_SUBSCRIBE_USER_NOTIFICATION);
                $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
                $mailto = $follwersName->username;
                $arrayFind = array('[username]', '[trainer_name]', '[classcoursename]', '[classCourseViewdetailsLink]');
                $arrayReplace = array($mailto, $trainnername, $classCourseName, $viewClassLink);
                $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                $subject = $mailmodel->subject;
                $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                try {
                    SkillSendMail::SendMail($mailto, $subject, $body);
                } catch (Exception $e) {
                    echo $e;
                    exit;
                }
            }
        }
    }

    public function actionCourseImage() {
        Yii::import("xupload.models.XUploadForm");
        $photos = new XUploadForm;
        $userImages = '';
        $modelClassImage = new ClassImage;
        $userImages = Yii::app()->user->getState('courseImage');
        $authKey = Yii::app()->user->getState('authKey');
        if (!empty($authKey)) {
            $courses = Courses::model()->findByAttributes(array('auth_key' => $authKey));
            $userId = getLoginUserId();
            if (!empty($courses) && ($userId == $courses->users_id)) {
                if (isset($_POST) && !empty($userImages)) {
                    try {
                        $classCourseImage = ClassImage::model()->findByAttributes(array('courses_id' => $courses->id));
                        $save = self::addcourseImage($courses->id);
                        Yii::app()->user->setState('courseImage', NULL);
                        if ($save) {
                            if (empty($classCourseImage)) {
                                $mailmodel = EmailTemplate::model()->findByPk(Message::CREATE_CLASS_COURSE_SUBSCRIBE_USER_NOTIFICATION);
                                $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
                                $userNames = Users::getFrontEndUser($courses->users_id);
                                $userName = $userNames->first_name . '  ' . $userNames->last_name;
                                $mailto = EMAIL_TO_ADMIN;
                                $classCourseName = $courses->course_titile;
                                $viewClassLink = '<a href="http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('courses-' . $courses->id . '/' . $courses->course_seo_title) . '" class="linkclass" target="_blank">View ' . SkillConfig::Course_WORK_SHOP . '</a>';
                                $this->sendMailToSubscribeUser($viewClassLink, $classCourseName, $userName);
                                $arrayFind = array('[username]', '[trainer_name]', '[classcoursename]', '[classCourseViewdetailsLink]');
                                $arrayReplace = array($mailto, $userName, $classCourseName, $viewClassLink);
                                $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                                $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                                $subject = $mailmodel->subject . '' . $userName;
                                $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                                try {
                                    SkillSendMail::SendMailCreateCLassCourse($mailto, $subject, $body);
                                    $this->redirect(array('classImage/createcoursesuccess' . $courses->id));
                                } catch (Exception $e) {
                                    echo $e;
                                    exit;
                                }
                            }
                            Yii::app()->user->setState('courseImage', null);
                            if (Yii::app()->getRequest()->getIsAjaxRequest())
                                Yii::app()->end();
                        }
                    } catch (Exception $e) {
                        $transaction->rollback();
                        throw $e;
                    }
                }
                $this->render('_courseFrom', array(
                    'modelClassImage' => $modelClassImage,
                    'photos' => $photos, 'authKey' => $authKey
                ));
            }
        } else {
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
        }
    }

    private static function addcourseImage($courseId) {
        $uploadeDir = Yii::app()->getBasePath() . SkillConfig::getaftersaveClassCourseImagePath(getLoginUserId());
        $readUploadeDir = Yii::app()->getBasePath() . SkillConfig::getClassCourseImagePath(getLoginUserId());
        $userImages = Yii::app()->user->getState('courseImage');
        if (!empty($userImages)) {
            foreach ($userImages as $classImage) {
                $modelClassImage = new ClassImage;
                if (file_exists("$readUploadeDir" . $classImage['filename'])) {
                    copy("$readUploadeDir" . $classImage['filename'], $uploadeDir . $classImage['filename']);
                    unlink("$readUploadeDir" . $classImage['filename']);
                }

                if (Yii::app()->user->hasState('coursePrimaryImage')) {
                    $primaryImage = Yii::app()->user->getState('coursePrimaryImage');
                    if ($primaryImage == $classImage["filename"]) {
                        $updateModel = ClassImage::model()->find('courses_id=:courses_id AND primary_image=:primary_image', array(':courses_id' => $courseId, 'primary_image' => SkillConfig::STATUS_ACTIVE));
                        if (!empty($updateModel)) {
                            ClassImage::model()->updateByPk($updateModel->id, array('primary_image' => '0'));
                        }
                        $modelClassImage->primary_image = 1;
                    }
                }
                $modelClassImage->photo = $classImage["filename"];
                $modelClassImage->courses_id = $courseId;
                $modelClassImage->save(false);
            }
        }
        return TRUE;
    }

    private static function addClassImage($classId) {
        $uploadeDir = Yii::app()->getBasePath() . SkillConfig::getaftersaveClassCourseImagePath(getLoginUserId());
        $readUploadeDir = Yii::app()->getBasePath() . SkillConfig::getClassCourseImagePath(getLoginUserId());
        $userImages = Yii::app()->user->getState('frontImages');
        if (!empty($userImages)) {
            foreach ($userImages as $classImage) {
                $modelClassImage = new ClassImage;
                if (file_exists("$readUploadeDir" . $classImage['filename'])) {
                    copy("$readUploadeDir" . $classImage['filename'], $uploadeDir . $classImage['filename']);
                    unlink("$readUploadeDir" . $classImage['filename']);
                }

                if (Yii::app()->user->hasState('primaryImage')) {
                    $primaryImage = Yii::app()->user->getState('primaryImage');
                    if ($primaryImage == $classImage["filename"]) {
                        $updateModel = ClassImage::model()->find('classes_id=:classes_id AND primary_image=:primary_image', array(':classes_id' => $classId, 'primary_image' => SkillConfig::STATUS_ACTIVE));
                        if (!empty($updateModel)) {
                            ClassImage::model()->updateByPk($updateModel->id, array('primary_image' => '0'));
                        }
                        $modelClassImage->primary_image = 1;
                    }
                }
                $modelClassImage->photo = $classImage["filename"];
                $modelClassImage->classes_id = $classId;
                $modelClassImage->save(false);
            }
        }
        return TRUE;
    }

    public function actionmakePrimaryImage() {
        Yii::app()->user->setState('primaryImage', NULL);
        $imagename = $_POST['imagename'];
        $newImagename = explode('/', $imagename);
        Yii::app()->user->setState('primaryImage', end($newImagename));
    }

    public function actioncoursePrimaryImage() {
        Yii::app()->user->setState('coursePrimaryImage', NULL);
        $imagename = $_POST['imagename'];
        $newImagename = explode('/', $imagename);
        Yii::app()->user->setState('coursePrimaryImage', end($newImagename));
    }

    public function actionprimaryImage() {
        $updateModel = ClassImage::model()->find('classes_id=:classes_id AND primary_image=:primary_image', array(':classes_id' => (int) $_POST['classid'], 'primary_image' => SkillConfig::STATUS_ACTIVE));
        if (!empty($updateModel)) {
            ClassImage::model()->updateByPk($updateModel->id, array('primary_image' => '0'));
        }
        $model = $this->loadModel($_POST['id'], 'ClassImage');
        $model->primary_image = '1';
        $model->save();
        echo CJSON::encode($model->getAttributes());
        Yii::app()->end();
    }

    public function actionCourseimageStatus() {
        $updateModel = ClassImage::model()->find('courses_id=:courses_id AND primary_image=:primary_image', array(':courses_id' => (int) $_POST['courseid'], 'primary_image' => SkillConfig::STATUS_ACTIVE));
        if (!empty($updateModel)) {
            ClassImage::model()->updateByPk($updateModel->id, array('primary_image' => '0'));
        }
        $model = $this->loadModel($_POST['id'], 'ClassImage');
        $model->primary_image = '1';
        $model->save();
        echo CJSON::encode($model->getAttributes());
        Yii::app()->end();
    }

    public function actiondeleteClassImage() {
        $uploadeDir = Yii::app()->getBasePath() . SkillConfig::getClassCourseImagePath(getLoginUserId());
        $idList = Yii::app()->request->getParam('idList');
        $allIds = (is_array($idList)) ? implode(',', $idList) : $idLsit;
        $classImageId = explode(',', $allIds);
        for ($i = 0; $i < count($classImageId); $i++) {
            $imageName = ClassImage::model()->find('id=:id ', array(':id' => (int) $classImageId[$i]));
            if (file_exists("$uploadeDir" . 'details-image/' . $imageName->photo)) {
                unlink("$uploadeDir" . 'details-image/' . $imageName->photo);
            }
            if (file_exists("$uploadeDir" . 'image/' . $imageName->photo)) {
                unlink("$uploadeDir" . 'image/' . $imageName->photo);
            }
            if (file_exists("$uploadeDir" . 'slider-image/' . $imageName->photo)) {
                unlink("$uploadeDir" . 'slider-image/' . $imageName->photo);
            }
            if (file_exists("$uploadeDir" . 'thumbs/' . $imageName->photo)) {
                unlink("$uploadeDir" . 'thumbs/' . $imageName->photo);
            }
        }

        $sql = "DELETE FROM skill_class_image WHERE id IN($allIds)";
        $cmd = Yii::app()->db->createCommand($sql);
        $cmd->execute();
// $this->actionIndex();
    }

    public function actionUpload() {
        Yii::import("xupload.models.XUploadForm");
        $publicPath = getRequestbaseUrl() . getuploadFolderDir() . SkillConfig::getClassCourseImagethumbsPath(getLoginUserId());
        $path = getUploadDir() . SkillConfig::getClassCourseImagePath(getLoginUserId());
        header('Vary: Accept');
        if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
            header('Content-type: application/json');
        } else {
            header('Content-type: text/plain');
        }
        if (isset($_GET["_method"])) {
            if ($_GET["_method"] == "delete") {
                if ($_GET["file"][0] !== '.') {
                    $file = $path . $_GET["file"];
                    if (is_file($file)) {
                        unlink($file);
                    }
                }
                echo json_encode(true);
            }
        } else {
            $model = new XUploadForm;
            $model->file = CUploadedFile::getInstance($model, 'file');
            if ($model->file !== null) {
                $filenameExt = '';
                $model->mime_type = $model->file->getType();
                $model->size = $model->file->getSize();
                $model->name = $model->file->getName();
//(optional) Generate a random name for our file
                $filename = md5(Yii::app()->user->id . microtime() . $model->name);
                $filenameExt.= "." . $model->file->getExtensionName();
                $newFilename = $filename . $filenameExt;
                if ($model->validate()) {
                    $model->file->saveAs($path . $newFilename);
                    $newimage = $path . $newFilename;
                    $image = Yii::app()->image->load($newimage);
                    $image->resize(CLASS_IMAGE_WIDTH, CLASS_IMAGE_HEIGHT, Image::NONE);
                    $image->save($path . '/thumbs/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                    $detailsimage = Yii::app()->image->load($newimage);
                    $detailsimage->resize(CLASS_IMAGE_DETAILS_WIDTH, CLASS_IMAGE_DETAILS_HEIGHT, Image::NONE);
                    $detailsimage->save($path . '/details-image/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                    $sliderimage = Yii::app()->image->load($newimage);
                    $sliderimage->resize(CLASS_IMAGE_SLIDER_WIDTH, CLASS_IMAGE_SLIDER_HEIGHT, Image::NONE);
                    $sliderimage->save($path . '/slider-image/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                    $userListImage = Yii::app()->image->load($newimage);
                    $userListImage->resize(CLASS_IMAGE_USERLIST_WIDTH, CLASS_IMAGE_USERLIST_HEIGHT, Image::NONE);
                    $userListImage->save($path . '/240X180/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                     //home category image
                    $homecategory = Yii::app()->image->load($newimage);
                    $homecategory->resize(CLASS_IMAGE_HOME_CATEGORY_WIDTH, CLASS_IMAGE_HOME_CATEGORY_HIEGHT, Image::NONE);
                    $homecategory->save($path . '/207X145/' . $newFilename);
                    chmod($path . $newFilename, 0777);


                    if (Yii::app()->user->hasState('frontImages')) {
                        $userImages = Yii::app()->user->getState('frontImages');
                    } else {
                        $userImages = array();
                    }
                    $userImages[] = array(
                        "path" => $path . $newFilename,
                        "thumb" => $path . '/thumbs/' . $newFilename,
                        "filename" => $newFilename,
                        'size' => $model->size,
                        'mime' => $model->mime_type,
                        'name' => $model->name,
                    );
                    Yii::app()->user->setState('frontImages', $userImages);
                    echo json_encode(array(array(
                            "name" => $model->name,
                            "type" => $model->mime_type,
                            "size" => $model->size,
                            "url" => $publicPath . $newFilename,
                            "thumbnail_url" => $publicPath . $newFilename,
                            "delete_url" => $this->createUrl("upload", array(
                                "_method" => "delete",
                                "file" => $newFilename
                            )),
                            "delete_type" => "POST"
                            )));
                } else {
//If the upload failed for some reason we log some data and let the widget know
                    echo json_encode(array(
                        array("error" => $model->getErrors('file'),
                            )));
                    Yii::log("XUploadAction: " . CVarDumper::dumpAsString($model->getErrors()), CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction"
                    );
                }
            } else {
                throw new CHttpException(500, "Could not upload file");
            }
        }
    }

    public function actionCourseupload() {
        Yii::import("xupload.models.XUploadForm");
        $publicPath = getRequestbaseUrl() . getuploadFolderDir() . SkillConfig::getClassCourseImagethumbsPath(getLoginUserId());
        $path = getUploadDir() . SkillConfig::getClassCourseImagePath(getLoginUserId());
        header('Vary: Accept');
        if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
            header('Content-type: application/json');
        } else {
            header('Content-type: text/plain');
        }
        if (isset($_GET["_method"])) {
            if ($_GET["_method"] == "delete") {
                if ($_GET["file"][0] !== '.') {
                    $file = $path . $_GET["file"];
                    if (is_file($file)) {
                        unlink($file);
                    }
                }
                echo json_encode(true);
            }
        } else {
            $model = new XUploadForm;
            $model->file = CUploadedFile::getInstance($model, 'file');
            if ($model->file !== null) {
                $filenameExt = '';
                $model->mime_type = $model->file->getType();
                $model->size = $model->file->getSize();
                $model->name = $model->file->getName();
//(optional) Generate a random name for our file
                $filename = md5(Yii::app()->user->id . microtime() . $model->name);
                $filenameExt.= "." . $model->file->getExtensionName();
                $newFilename = $filename . $filenameExt;
                if ($model->validate()) {
                    $model->file->saveAs($path . $newFilename);
                    $newimage = $path . $newFilename;
                    $image = Yii::app()->image->load($newimage);
                    $image->resize(CLASS_IMAGE_WIDTH, CLASS_IMAGE_HEIGHT, Image::NONE);
                    $image->save($path . '/thumbs/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                    $detailsimage = Yii::app()->image->load($newimage);
                    $detailsimage->resize(CLASS_IMAGE_DETAILS_WIDTH, CLASS_IMAGE_DETAILS_HEIGHT, Image::NONE);
                    $detailsimage->save($path . '/details-image/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                    $sliderimage = Yii::app()->image->load($newimage);
                    $sliderimage->resize(CLASS_IMAGE_SLIDER_WIDTH, CLASS_IMAGE_SLIDER_HEIGHT, Image::NONE);
                    $sliderimage->save($path . '/slider-image/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                    $userListImage = Yii::app()->image->load($newimage);
                    $userListImage->resize(CLASS_IMAGE_USERLIST_WIDTH, CLASS_IMAGE_USERLIST_HEIGHT, Image::NONE);
                    $userListImage->save($path . '/240X180/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                     //home category image
                    $homecategory = Yii::app()->image->load($newimage);
                    $homecategory->resize(CLASS_IMAGE_HOME_CATEGORY_WIDTH, CLASS_IMAGE_HOME_CATEGORY_HIEGHT, Image::NONE);
                    $homecategory->save($path . '/207X145/' . $newFilename);
                    chmod($path . $newFilename, 0777);


                    if (Yii::app()->user->hasState('courseImage')) {
                        $userImages = Yii::app()->user->getState('courseImage');
                    } else {
                        $userImages = array();
                    }
                    $userImages[] = array(
                        "path" => $path . $newFilename,
                        "thumb" => $path . '/thumbs/' . $newFilename,
                        "filename" => $newFilename,
                        'size' => $model->size,
                        'mime' => $model->mime_type,
                        'name' => $model->name,
                    );
                    Yii::app()->user->setState('courseImage', $userImages);
                    echo json_encode(array(array(
                            "name" => $model->name,
                            "type" => $model->mime_type,
                            "size" => $model->size,
                            "url" => $publicPath . $newFilename,
                            "thumbnail_url" => $publicPath . $newFilename,
                            "delete_url" => $this->createUrl("upload", array(
                                "_method" => "delete",
                                "file" => $newFilename
                            )),
                            "delete_type" => "POST"
                            )));
                } else {
//If the upload failed for some reason we log some data and let the widget know
                    echo json_encode(array(
                        array("error" => $model->getErrors('file'),
                            )));
                    Yii::log("XUploadAction: " . CVarDumper::dumpAsString($model->getErrors()), CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction"
                    );
                }
            } else {
                throw new CHttpException(500, "Could not upload file");
            }
        }
    }

}
